/*滚动加载搜索结果*/
var LoadWaterfulData = {
	"nextPage": 1,
	"keyword": RatingbaySearch['keyword'],
	"nextWaterUrl": function(){
		var keyword = LoadWaterfulData['keyword'];
		var pageNum = LoadWaterfulData['nextPage'];
		var url = "rest/game/"
				+ (LoadWaterfulData.F?"getOrderedGameWaters/":"getGameWaters/")
				+ keyword
				+ "/"
				+ (LoadWaterfulData.F?(LoadWaterfulData.F+"/"):"")
				+ (LoadWaterfulData.D?(LoadWaterfulData.D+'/'):'')
				+ pageNum
				+ ".do";
		return url;
	},
	'hasNext': true,
	'isLoading':false,
	'timer':null,
	'F':'',
	'D':''
};

$(window).on('scroll',function(){
	if(!$('.search-result-list').length)
		return;
	if(!LoadWaterfulData.isLoading&&LoadWaterfulData.hasNext){
		clearTimeout(LoadWaterfulData.timer);
		LoadWaterfulData.timer = setTimeout(function(){
			srollLoading($('#search-wrapper .search-box'));
		},200);
	}

});

$('.order-btn').on('click',function(){
	if($(this).hasClass('order-btn-active')){
		if($(this).hasClass('order-desc')){
			$(this).removeClass('order-desc').addClass('order-asc');
		}else{
			$(this).removeClass('order-asc').addClass('order-desc');
		}
	}
	reorderResult($(this));
});

var srollLoading = function(contentBox){
	var list = contentBox.find('ul.list')
		,H = contentBox.offset().top+contentBox.height()
		,bodyH = $(document.body).height()
		,st = $(window).scrollTop();

	if(st+bodyH>=H){
		loadMoreData(contentBox);
	}
}


var reorderResult = function($btn){
	LoadWaterfulData.F = $btn.attr('id');
	LoadWaterfulData.D = $btn.hasClass('order-desc')?'DESC':'ASC';
	LoadWaterfulData.isOrdering = true;
	$btn.parent().find('.order-btn-active').removeClass('order-btn-active');
	$btn.addClass('order-btn-active');
	LoadWaterfulData.nextPage = 0;	//重新调整nextPage
	LoadWaterfulData.hasNext = true;	//设置
	LoadWaterfulData.lastOrderRequest&&LoadWaterfulData.lastOrderRequest.abort();	//中断上次请求
	$('#loading-status').remove();	//remove loading status
	LoadWaterfulData.lastOrderRequest = loadMoreData($('#search-wrapper .search-box'),function(){
		$('#search-wrapper .search-box').find('ul').empty();
	});
}

function loadMoreData(contentBox,callback){

	var statusDOM = $('<p id="loading-status" style="text-align:center;">').html('Loading content...');
	contentBox.append(statusDOM);
	LoadWaterfulData.isLoading = true;
	var url = LoadWaterfulData["nextWaterUrl"]()
		,list = contentBox.find('ul.list');

	var req = $.get(url,function(data){
			if(data&&data.content){
				callback&&callback();
				list.append($(data.content));
				LoadWaterfulData.isLoading = false;
				LoadWaterfulData.nextPage += 1;
				radialProgress(list);
				if(!data.hasNext){
					LoadWaterfulData['hasNext'] = false;
					statusDOM.text("It's the end,try to search other words");
				}else{
					statusDOM.remove();
				}
			}
		});
	return req;
}